package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单定时任务处理类
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;
    /**
     * 处理超时订单定时任务
     */
    //@Scheduled(cron = "0 * * * * ?")//每分钟执行一次
    public void processOverTimeOrder(){
        log.info("处理超时订单定时任务");

        //1.查询超时订单
        // select * from orders where status = 1 and order_time  <= 当前时间-15
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime time = now.plusMinutes(-15);
        List<Orders> ordersList = orderMapper.getOrderByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);
        if (!CollectionUtils.isEmpty(ordersList)){
            //2.修改超时订单
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(now);
                orders.setCancelReason("超时未支付");
            }
            orderMapper.updateBatch(ordersList);
        }
    }

    /**
     * 处理的派送中订单
     */
    //@Scheduled(cron = "0 0 1 * * ?")//凌晨一点执行一次
    //@Scheduled(cron = "0/5 *  * * ?")//每5s执行一次
    public void processDeliverOrder(){
        log.info("处理的派送中订单");
        //1.查询派送中订单
        List<Orders> ordersList = orderMapper.getOrderByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,LocalDateTime.now());
        //2.修改订单状态
        if (!CollectionUtils.isEmpty(ordersList)){
            //2.修改超时订单
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
            }
            orderMapper.updateBatch(ordersList);
        }
    }
}
